package com.finance.console.service.analysis;

// 补充必要导入（保持你的包路径）
import com.finance.console.dao.IncomeExpenseDAO;
import com.finance.console.entity.AnalysisResult;
import com.finance.console.entity.IncomeExpense;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.math.BigDecimal;

public class ConsumptionAnalysisService {
    // 保持你的DAO实例命名
    private final IncomeExpenseDAO recordDAO = new IncomeExpenseDAO();
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");

    public AnalysisResult analyzeMonth(int userId, String yearMonth) {
        try {
            // 1. 解析日期（保持你的逻辑）
            Date monthStart = sdf.parse(yearMonth);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(monthStart);
            calendar.add(Calendar.MONTH, 1);
            calendar.add(Calendar.DAY_OF_MONTH, -1);
            Date monthEnd = calendar.getTime();

            // 2. 获取所有支出类型（保持你的硬编码）
            List<String> expenseTypes = Arrays.asList("餐饮", "交通", "住房", "娱乐", "购物");
            Map<String, BigDecimal> typeExpense = new HashMap<>();
            for (String type : expenseTypes) {
                // 调用DAO方法（参数和命名完全不变）
                BigDecimal amount = recordDAO.sumExpenseByType(userId, type, monthStart, monthEnd);
                typeExpense.put(type, amount != null ? amount : BigDecimal.ZERO); // 避免null
            }

            // 3. 计算消费占比和最高消费类型（保持你的逻辑）
            BigDecimal totalExpense = typeExpense.values().stream()
                    .reduce(BigDecimal.ZERO, BigDecimal::add);
            Map<String, Double> consumeRatio = new HashMap<>();
            String topType = "";
            BigDecimal maxAmount = BigDecimal.ZERO;

            for (Map.Entry<String, BigDecimal> entry : typeExpense.entrySet()) {
                String type = entry.getKey();
                BigDecimal amount = entry.getValue();

                // 计算占比（补充除零保护，保持你的逻辑）
                double ratio = totalExpense.compareTo(BigDecimal.ZERO) == 0 ?
                        0 : amount.divide(totalExpense, 4, BigDecimal.ROUND_HALF_UP).doubleValue() * 100;
                consumeRatio.put(type, ratio);

                // 判断最高消费类型
                if (amount.compareTo(maxAmount) > 0) {
                    maxAmount = amount;
                    topType = type;
                }
            }

            // 4. 封装结果（假设AnalysisResult有这些setter）
            AnalysisResult result = new AnalysisResult();
            result.setPeriod(yearMonth);
            result.setTopConsumeType(topType);
            result.setConsumeRatio(consumeRatio);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}